package com.xiaoxi.checkpasswordserver.service.impl;

import com.xiaoxi.checkpasswordserver.domain.*;
import com.xiaoxi.checkpasswordserver.service.CheckPasswordService;
import com.xiaoxi.domain.password.VerifyPassword;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author xiaoxi
 * @ProjectName springcloudbms
 * @PackageName com.xiaoxi.checkpassword.service.impl
 * @ClassName CheckPasswordServiceImpl
 * @Description TODO
 * @Date 2023/2/8 19:06
 * @Version 1.0
 */
@Service
public class CheckPasswordServiceImpl implements CheckPasswordService {

    @Resource
    private Map<String, IPasswordCheck> passwordCheckMap;

    @Override
    public CheckResult checkPassword(VerifyPassword verifyPassword) {

        CheckResult checkResult = new CheckResult();

        ConfirmPasswordCheck confirmPasswordCheck = new ConfirmPasswordCheck();
        confirmPasswordCheck.setConfirmPassword(verifyPassword.getConfirmPassword());

        ContainUserNameCheck containUserNameCheck = new ContainUserNameCheck();
        containUserNameCheck.setUserName(verifyPassword.getUsername());

        passwordCheckMap.put("confirmPasswordCheck", confirmPasswordCheck);
        passwordCheckMap.put("containUserNameCheck", containUserNameCheck);

        // 3. 校验密码
        for (Map.Entry<String, IPasswordCheck> map : passwordCheckMap.entrySet()) {
            map.getValue().check(verifyPassword.getNewPassword(), checkResult);
        }

        // 4. 查看检查的结果
        recheckResult(checkResult);
        return checkResult;

    }

    /**
     * 通过 每一系列检查的结果 找到准确错误
     *
     * @param checkResult
     */
    private void recheckResult(CheckResult checkResult) {

        StringBuilder stringBuilder = new StringBuilder();
        int i;
        if (checkResult.getErrorReason().size() > 0) {
            for (i = 0; i < checkResult.getErrorReason().size(); ++i) {
                if (stringBuilder.length() > 0) {
                    stringBuilder.append(",");
                }

                stringBuilder.append(checkResult.getErrorReason().get(i));
            }
        }

        if (checkResult.getConfirmCount() < 3) {

            if (stringBuilder.length() > 0) {
                stringBuilder.append(",");
            }
            stringBuilder.append("密码应包含");
            for (i = 0; i < checkResult.getConfirmInfo().size(); ++i) {
                stringBuilder.append(checkResult.getConfirmInfo().get(i));
                if (i < checkResult.getConfirmInfo().size() - 1) {
                    stringBuilder.append("、");
                }
            }
            stringBuilder.append("至少");
            stringBuilder.append(3 - checkResult.getConfirmCount());
            stringBuilder.append("项");
        }

        if (stringBuilder.length() > 0) {
            checkResult.setConclusion(stringBuilder.toString());
        }

    }
}
